﻿using Newtonsoft.Json.Linq;
using Serilog;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Web;

namespace Coldairarrow.Util.lib
{
    public class wxGetOpenid
    {
        #region 获取微信登陆openid和session_key
        /// <summary>
        /// 获取微信登陆openid和session_key
        /// </summary>
        /// <param name="code">code</param>
        public static JObject Getopenid(string AppID, string Secret, string code)
        {
            string Data = "";

            IDictionary<string, string> parameters = new Dictionary<string, string>();
            parameters.Add("appId", AppID);
            parameters.Add("secret", Secret);
            parameters.Add("js_code", code);
            parameters.Add("grant_type", "authorization_code");
            Data = sendPost("https://api.weixin.qq.com/sns/jscode2session", parameters, "GET");

            JObject jObject = JObject.Parse(Data);

            if (jObject["errcode"] != null)
            {
                if (jObject["errcode"].ToString().Equals("40163"))
                {
                    throw new BusException("Code码已被使用，错误代码：40163,请检查代码！", errorCode: -2);
                }
                else
                {
                    throw new BusException("获取OpenId失败，错误代码:" + jObject["errcode"].ToString()+ ",请检查代码！", errorCode: -3);
                }
            }
            else
            {
                return jObject;
            }
        }

        /// <summary>
        /// 获取微信登陆openid和session_key
        /// </summary>
        /// <param name="code">code</param>
        public static JObject GetWebopenid(string AppID, string Secret, string code)
        {
            string Data = "";
            Log.Information("AppId={0}", AppID);
            Log.Information("Secret={0}", Secret);
            Log.Information("code={0}", code);

            IDictionary<string, string> parameters = new Dictionary<string, string>();
            parameters.Add("appId", AppID);
            parameters.Add("secret", Secret);
            parameters.Add("code", code);
            parameters.Add("grant_type", "authorization_code");
            Data = sendPost("https://api.weixin.qq.com/sns/oauth2/access_token", parameters, "GET");

            JObject jObject = JObject.Parse(Data);

            if (jObject["errcode"] != null)
            {
                if (jObject["errcode"].ToString().Equals("40163"))
                {
                    throw new BusException("Code码已被使用，错误代码：40163,请检查代码！", errorCode: -2);
                }
                else
                {
                    throw new BusException("获取OpenId失败，错误代码:" + jObject["errcode"].ToString() + ",请检查代码！", errorCode: -3);
                }
            }
            else
            {
                return jObject;
            }
        }

        /// <summary>
        /// 获取微信登陆openid和session_key
        /// </summary>
        /// <param name="OpenId">OpenId</param>
        /// <param name="access_token">access_token</param>
        public static JObject GetUserInfo(string AppID, string Secret,string OpenId, string access_token)
        {
            string Data = "";
            Log.Information("openid={0}", OpenId);
            Log.Information("access_token={0}", access_token);

            IDictionary<string, string> parameters = new Dictionary<string, string>();
            parameters.Add("openid", OpenId);
            parameters.Add("access_token", access_token);
            Data = sendPost("https://api.weixin.qq.com/sns/userinfo", parameters, "GET");

            JObject jObject = JObject.Parse(Data);

            if (jObject["errcode"] != null)
            {  
              throw new BusException("获取userinfo失败，错误代码:" + jObject["errcode"].ToString() + ",请检查代码！", errorCode: -3);
            }
            else
            {
                return jObject;
            }
        }

        public static string HttpGet(string url)
        {
            HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
            httpWebRequest.Method = "GET";
            httpWebRequest.Accept = "*/*";
            string str = "";
            using (HttpWebResponse response = (HttpWebResponse)httpWebRequest.GetResponse())
            {
                using (StreamReader streamReader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.UTF8))
                    str = streamReader.ReadToEnd();
            }
            return str;
        }

        #endregion
        #region Http (GET/POST)
        /// <summary>
        /// Http (GET/POST)
        /// </summary>
        /// <param name="url">请求URL</param>
        /// <param name="parameters">请求参数</param>
        /// <param name="method">请求方法</param>
        /// <returns>响应内容</returns>
        public static string sendPost(string url, IDictionary<string, string> parameters, string method)
        {
            if (method.ToLower() == "post")
            {
                HttpWebRequest req = null;
                HttpWebResponse rsp = null;
                System.IO.Stream reqStream = null;
                try
                {
                    req = (HttpWebRequest)WebRequest.Create(url);
                    req.Method = method;
                    req.KeepAlive = false;
                    req.ProtocolVersion = HttpVersion.Version10;
                    req.Timeout = 5000;
                    req.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
                    byte[] postData = Encoding.UTF8.GetBytes(BuildQuery(parameters, "utf8"));
                    reqStream = req.GetRequestStream();
                    reqStream.Write(postData, 0, postData.Length);
                    rsp = (HttpWebResponse)req.GetResponse();
                    Encoding encoding = Encoding.GetEncoding(rsp.CharacterSet);
                    return GetResponseAsString(rsp, encoding);
                }
                catch (Exception ex)
                {
                    return ex.Message;
                }
                finally
                {
                    if (reqStream != null) reqStream.Close();
                    if (rsp != null) rsp.Close();
                }
            }
            else
            {
                //创建请求
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url + "?" + BuildQuery(parameters, "utf8"));

                //GET请求
                request.Method = "GET";
                request.ReadWriteTimeout = 5000;
                request.ContentType = "text/html;charset=UTF-8";
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream myResponseStream = response.GetResponseStream();
                StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));

                //返回内容
                string retString = myStreamReader.ReadToEnd();
                return retString;
            }
        }
        #endregion
        #region 组装普通文本请求参数
        /// <summary>
        /// 组装普通文本请求参数。
        /// </summary>
        /// <param name="parameters">Key-Value形式请求参数字典</param>
        /// <returns>URL编码后的请求数据</returns>
        static string BuildQuery(IDictionary<string, string> parameters, string encode)
        {
            StringBuilder postData = new StringBuilder();
            bool hasParam = false;
            IEnumerator<KeyValuePair<string, string>> dem = parameters.GetEnumerator();
            while (dem.MoveNext())
            {
                string name = dem.Current.Key;
                string value = dem.Current.Value;
                // 忽略参数名或参数值为空的参数
                if (!string.IsNullOrEmpty(name))//&& !string.IsNullOrEmpty(value)
                {
                    if (hasParam)
                    {
                        postData.Append("&");
                    }
                    postData.Append(name);
                    postData.Append("=");
                    if (encode == "gb2312")
                    {
                        postData.Append(HttpUtility.UrlEncode(value, Encoding.GetEncoding("gb2312")));
                    }
                    else if (encode == "utf8")
                    {
                        postData.Append(HttpUtility.UrlEncode(value, Encoding.UTF8));
                    }
                    else
                    {
                        postData.Append(value);
                    }
                    hasParam = true;
                }
            }
            return postData.ToString();
        }
        #endregion
        #region 把响应流转换为文本
        /// <summary>
        /// 把响应流转换为文本。
        /// </summary>
        /// <param name="rsp">响应流对象</param>
        /// <param name="encoding">编码方式</param>
        /// <returns>响应文本</returns>
        static string GetResponseAsString(HttpWebResponse rsp, Encoding encoding)
        {
            System.IO.Stream stream = null;
            StreamReader reader = null;
            try
            {
                // 以字符流的方式读取HTTP响应
                stream = rsp.GetResponseStream();
                reader = new StreamReader(stream, encoding);
                return reader.ReadToEnd();
            }
            finally
            {
                // 释放资源
                if (reader != null) reader.Close();
                if (stream != null) stream.Close();
                if (rsp != null) rsp.Close();
            }
        }
        #endregion
    }
}